package com.lee.study.thrift.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ThriftNettyServer implements NettyServer {

    private final static Logger logger = LoggerFactory.getLogger(ThriftNettyServer.class);

    private int port;
    private Channel channel;

    private EventLoopGroup bossGroup;
    private EventLoopGroup workGroup;

    public ThriftNettyServer(int port) {
        this.port = port;
    }

    @Override
    public void serve() {
         bossGroup = new NioEventLoopGroup(1);
         workGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ThriftNettyHandlerInitializer());

            channel = serverBootstrap.bind(this.port).sync().channel();
            logger.info("server bind port " + this.port);
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            logger.error(e.getMessage());
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }

    public void stop() {
        bossGroup = new NioEventLoopGroup(1);
        workGroup = new NioEventLoopGroup();
    }
}
